package com.yjhh.hadoop.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.net.URI;

/**
 * Created by hlantian on 2017/11/5.
 */
public class WordCountApp {

    /**
     * 读取输入文件
     */
    public static class MyMap extends Mapper<LongWritable, Text, Text, LongWritable> {

        LongWritable one = new LongWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //接收到每一行数据
            String line = value.toString();
            //按照指定分割符进行拆分
            String[] words = line.split(" ");
            for (String word : words) {
                //通过哈桑下文把map的处理结果输出
                context.write(new Text(word), one);
            }
        }
    }

    /**
     * 归并操作
     */
    public static class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {

        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (LongWritable value : values) {
                //求key出现的次数总和
                sum += value.get();
            }
            //最终计算结果输出
            context.write(key, new LongWritable(sum));
        }


    }

    /**
     * 封装定义作业里的所有信息
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        //创建job
        Job job = Job.getInstance(configuration, "wordcount");

        //为了解决输出目录已经存在的问题，所以需要先将输出目录删除然后再执行任务
        Path outputDir = new Path(args[1]);
        FileSystem fs = FileSystem.get(URI.create("hdfs://Master:8020/"),configuration);
        if(fs.exists(outputDir)){
            fs.delete(outputDir,true);
            System.out.println("out folder exist,but deleted");
        }

        //设置job的处理类
        job.setJarByClass(WordCountApp.class);

        //设置作业处理的输入路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));

        //设置map相关参数
        job.setMapperClass(MyMap.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //设置reduce相关参数
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //设置作业处理的输出路径
        FileOutputFormat.setOutputPath(job, outputDir);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

}
